import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
// import { getToken } from '@/utils/auth'

export const request = (options: any) => {
  const router = useRouter()
  return new Promise((resolve, reject) => {
    // create an axios instance
    const service = axios.create({
      // baseURL: process.env.BASE_API, // api 的 base_url
      baseURL: 'http://127.0.0.1:7001',
      timeout: 80000, // request timeout
    })

    // request interceptor
    service.interceptors.request.use(
      (config: any) => {
        let token = sessionStorage.getItem('token')
        if (token) {
          //如果有token给请求头加上
          config.headers["Authorization"] = token
        }
        return config
      },
      (error) => {
        // Do something with request error
        Promise.reject(error)
      }
    )

    // response interceptor
    service.interceptors.response.use(
      (response: any) => {
        return response.data
      },
      (error) => {
        if (error.response.data.status === 403) {
          ElMessage.error('地址访问出错')
        } else if (error.response.data.status === 500) {
          ElMessage.error(error.response.data.message)
        } else if (error.response.data.code === 'invalid_token') {
          ElMessage.error('登录超时，请重新登录')
          router.go(0)
          window.localStorage.removeItem('token')
          router.replace({ path: '/login' })
        }
        return Promise.reject(error)
      }
    )
    // 请求处理
    service(options)
      .then((res) => {
        resolve(res)
      })
      .catch((error) => {
        reject(error)
      })
  })
}

export default request
